package com.core.family.gen.service.gen.Impl.oracel;

import com.core.family.gen.domain.po.TableBeanPo;
import com.core.family.gen.domain.po.TableColumnPo;
import com.core.family.gen.service.gen.Impl.AbsGenHandler;

import java.sql.*;
import java.util.*;

/**
 * @description: mybatis 相关代码生成 通过链接器获取数据库元信息实现
 * @author: honglei
 * @time: 2021/3/23 0023 14:48
 */

public class GenOracleHandler extends AbsGenHandler {

    //oracle 查询表名
    //   private final  static String QUEARY_TABLEAS = "select table_name as TABLE_NAME  tableName from user_tables ";
    private final static String QUEARY_TABLEAS =
            " select table_name as TABLE_NAME,COMMENTS  as REMARKS , TABLE_TYPE AS  TYPE" +
                    " from user_tab_comments ";


    //查询表字段及注释
    private final static String QUEARY_COLUMNS =
            " select t.column_name as COLUMN_NAME , p.COMMENTS as REMARKS, t.data_type  as TYPE_NAME " +
                    " from user_tab_columns  t LEFT JOIN user_col_comments  p on t.column_name = p.column_name " +
                    " where t.table_name= ?  and p.table_name= ? " +
                    " order by column_name ";


    @Override
    public List<TableBeanPo> tablesList() throws Exception {
        List<TableBeanPo> list = new ArrayList<>();

        if (list.size() == 0) {
            Connection connection = getConnection();
            ResultSet rs = connection.createStatement().executeQuery(QUEARY_TABLEAS);
            list = filledTableBean(rs);
            connection.clearWarnings();
        }
        return list;
    }


    @Override
    public List<TableColumnPo> getColumns(String table) throws Exception {

        List<TableColumnPo> list = new ArrayList<>();

        if (list.size() == 0) {
            Connection connection = getConnection();
            PreparedStatement ps = connection.prepareStatement(QUEARY_COLUMNS);
            ps.setString(1, table);
            ps.setString(2, table);
            ResultSet resultSet = ps.executeQuery();
            list = filledTableColumn(resultSet);
            connection.close();
        }
        return list;
    }
}
